#coding:utf-8
# from homeapp.models import TTest
from homeapp.DAL.tlog_dal import tlog_dal
from homeapp.models import TLog
from homeapp.models import RTLog_TNote
import uuid
import datetime
import time
from django.db import transaction

class tlog_service():

    @staticmethod
    def selectlog():

        # 目前是得到全部的selectlog
        return tlog_dal.selectlog()

    @staticmethod
    def selectbyguids(guids):
        return tlog_dal.selectbyguids(guids)

    @staticmethod
    def debugcount(guids):
        count = len(guids)
        return count

    @staticmethod
    def getlen(guids):
        return tlog_dal.getlen(guids)

    @staticmethod
    def processnewlog(title, guids):

        # 在这个函数内处理多个表的cud

        # 1. 创建一个日志对象
        thistime = time.localtime()
        strtime = time.strftime("%Y-%m-%d", thistime)
        newtlog = TLog(guid=str(uuid.uuid1())
                       , Title=title
                       , LogDateTime = datetime.datetime.strptime(strtime, "%Y-%m-%d"))

        # 2. 创建一系列日志记述关系对象
        rtlogtnotearr = []
        with transaction.atomic():
            try:
                newtlog.save()
                i = 0
                for guid in guids:
                    temprel = RTLog_TNote(guid=str(uuid.uuid1())
                                  , Note_Guid = guid
                                  , Log_Guid = newtlog.guid
                                  , order = i)
                    rtlogtnotearr.append(temprel)
                    i += 1
                    temprel.save()
            except:
                pass

        # 3. 使用事务保存这些对象
        # tlog_dal.addandrelation(newtlog, rtlogtnotearr)
        """
        with transaction.atomic():
            try:
                willaddTTest.save()
                willaddTTest2.save()
            except:
                pass
        """

        # 4. 返回0
        return 0
